<?php

namespace App\Helper;

use Dcat\Admin\Admin;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class Tool
{
    /**
     * 自定义分页方法
     * @param $collection
     * @param $perPage
     * @param null $fragment
     * @return LengthAwarePaginator
     */
    public static function pages($collection, $perPage, $fragment = null): LengthAwarePaginator
    {
        if (!$collection instanceof Collection){
            $collection = collect($collection);
        }
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        $currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage)->values();
        parse_str(request()->getQueryString(), $query);
        unset($query['page']);
        return new LengthAwarePaginator(
            $currentPageItems,
            $collection->count(),
            $perPage,
            $currentPage,
            [
                'pageName' => 'page',
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'query' => $query,
                'fragment' => $fragment
            ]
        );
    }

    /**
     * 启用JS websocket
     * @param int $shop_id
     * @return void
     */
    public static function websocket(int $shop_id = 0): void
    {
        admin_inject_section(Admin::SECTION['BODY_INNER_BEFORE'], function () use ($shop_id) {
            $serverName = request()->server('SERVER_NAME');
            $host = "wss://{$serverName}:8099";
            $type = $shop_id?"ping_shop":"ping_admin";
            $sendData = json_encode([
                "type"=>$type,
                "shop_id"=>$shop_id
            ]);
            return <<<HTML
<script>
    const openWebSocket = function (){
        let ws = new WebSocket("{$host}");
        let interval = null;
        ws.onopen = function (evt) {
            console.log("链接已打开.",evt);
            interval = setInterval(function (){
                ws.send('{$sendData}')
            },1500)
        };
        ws.onclose = function (evt) {
            console.log("链接已关闭",evt);
            clearInterval(interval)
            openWebSocket();
        };
        ws.onmessage = function (evt) {
            const data = JSON.parse(evt.data);
            if (data.type==='newCount'&&data.count){
                Dcat.swal.success('有新的数据处理', "待处理的服务订单:"+data.count+"条");
            }
        };
        ws.onerror = function (evt, e) {
            console.log('链接错误: ',evt);
        };
        window.ws_send = (data)=>{
            ws.send(data);
        }

    }
    openWebSocket();
</script>
HTML;
        });
    }
}
